import React, { Component, PropTypes } from 'react';
import { connect } from "react-redux";
import { setWaterMarkConfig } from 'actions/main'
import configureStore from "stores";

/**
 * 水印组件，这里偷懒要求放在已定位的元素内即可
 * 可以写的更高级（包裹组件、自动监听全局配置）一点，但是没必要
 */
class WaterMark extends Component {

  img = null;

  createWaterMarkImg = () => {
    const { waterMarkConfig } = this.props;
    const { text, fontSize, color, width, height } = { ...waterMarkConfig, ...this.props };
    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    canvas.width = width;
    canvas.height = height;
    context.fillStyle = color;
    context.font = fontSize * 2 + "px Arial";
    context.textBaseline = 'middle';
    context.scale(.5 , .5);
    context.fillText(text, 0, fontSize);
    context.fillText(text, width, height + fontSize);
    return canvas.toDataURL('image/png');
  };

  render() {
    const { waterMarkConfig, style } = this.props;
    const { reg, disabled } = { ...waterMarkConfig, ...this.props };
    //不支持这个属性则水印无法使用，将会盖住所有元素不可操作
    const supportPointerEvents = 'pointerEvents' in document.body.style;
    if(supportPointerEvents && !disabled) {
      if(!this.img)
        this.img = this.createWaterMarkImg();
      //下面用了双倍的大小，是为了防止旋转后缺角
      //其实这里直接用两倍是不准确的，需要计算父元素的宽高和旋转的角度进行计算
      return <div
        style={{
          width: '100%',
          height: '100%',
          overflow: 'hidden',
          position: 'absolute',
          pointerEvents: 'none',
          zIndex: 9999,
          ...style
        }}
      >
        <div
          style={{
            position: 'absolute',
            left: '-50%',
            top: '-50%',
            bottom: '-50%',
            right: '-50%',
            background: `url("${this.img}") repeat`,
            pointerEvents: 'none',
            transform: `rotateZ(${reg}deg)`,
            WebkitTransform: `rotateZ(${reg}deg)`,
            MsTransform: `rotateZ(${reg}deg)`,
            MozTransform: `rotateZ(${reg}deg)`
          }}
        />
      </div>
    } else {
      return null;
    }
  }

  static propTypes = {
    text: PropTypes.string,
    fontSize: PropTypes.number,
    color: PropTypes.string,
    reg: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
    disabled: PropTypes.bool,
    style: PropTypes.object
  };

}

WaterMark.config = function(config) {
  configureStore.store.dispatch(setWaterMarkConfig(config));
};

function mapStateToProps(state) {
  return {
    waterMarkConfig: state.main.waterMarkConfig
  }
}

export default connect(mapStateToProps)(WaterMark);
